package com.baidu.disk.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;
/**
 * Created by CJ on 2018-03-28.
 */
public class FileDown {

    public static void main(String[] args) {



            //保存当地文件位置
            String localDir = "F:\\";

            downloadFileFromURL("", localDir, "a.pdf");

    }

    /**
     * 将文件中的内容入读到一个List中
     * @param fileName
     * @return
     */
    public static List<String> readFileToList(String fileName) {
        List<String> fileNameList = new ArrayList<String>();
        FileInputStream fileInputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;

        try {
            fileInputStream = new FileInputStream(fileName);
            inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
            bufferedReader = new BufferedReader(inputStreamReader);
            String line = null;
            while((line = bufferedReader.readLine()) != null) {
                fileNameList.add(line.trim());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if(bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        /**
         * 关闭打开的各种流
         */
        if(inputStreamReader != null) {
            try {
                inputStreamReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if(fileInputStream != null) {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return fileNameList;
    }

    /**
     * 从URL下载文件
     * @param url 下载文件的路径
     * @param
     * @param dirLocation 保存下载文件的位置
     * @return
     */
    public static String downloadFileFromURL(String url, String dirLocation, String fileName) {
        try {
            URL httpUrl = new URL(url);

            File file = new File(dirLocation + fileName);
            file.createNewFile();
            FileUtils.copyURLToFile(httpUrl, file);
            System.out.println("下载文件 " + fileName + "成功!");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("下载文件 " + fileName + "失败!");
        }
        return null;
    }

}